<%@ page pageEncoding="UTF-8"%>
<%@ page import="java.util.Map.Entry,java.util.*,java.util.regex.*,java.net.*,java.io.*,java.text.*"%>
<%@ page import="com.tianxiabuyi.*,com.tianxiabuyi.db.*,com.tianxiabuyi.model.*,com.tianxiabuyi.util.*"%>
<%@ page import="org.jsoup.Jsoup,org.jsoup.nodes.Element,org.jsoup.select.Elements"%>
<%@ page import="com.google.gson.reflect.TypeToken"%>
<%@ page import="org.dom4j.*"%>
<%!	
	// 检查时间
	public int checkTime(String str) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd EEEE");
			Date dateNow = sdf.parse(str);
			sdf = new SimpleDateFormat("yyyy-MM-dd");
			String date = sdf.format(dateNow);
			boolean flag = date.equals(DateUtil.formatDateByFormat(new Date(), "yyyy-MM-dd"));
			if(!flag) {
				return 3;
			}
			date += " " + DateUtil.formatDateByFormat(new Date(), "HH:mm");
			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String lowStr = DateUtil.formatDate(new Date()) + " " + "09:00";
			String highStr = DateUtil.formatDate(new Date()) + " " + "12:00";
			if (sdf.parse(highStr).getTime() < sdf.parse(date).getTime()) {
				return 2;
			}
			if (sdf.parse(lowStr).getTime() < sdf.parse(date).getTime()) {
				return 1;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public String[] weeks_check = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
	public int getIndex(String week){
		String[] weeks = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
		int index = 0;
		for (int i = 0; i < weeks.length; i++) {
			if(weeks[i].equals(week)) {
				index = i;
				break;
			}
		}
		return index;
	}
	
	//传入星期与要获取的几周
	public List<Map> getPeriodOfTime(String week, int next){
		List<Map> list = new ArrayList<Map>();
		try{
			Calendar cal = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
			String startTime = sdf.format(cal.getTime());
			int diff = getIndex(week) - getIndex(startTime);
			cal.add(Calendar.DAY_OF_MONTH, diff);
			sdf = new SimpleDateFormat("yyyy-MM-dd EEEE");
			for (int i = 0, j = (diff >= 0 ? 0 : 1); i < next; j = 1, i ++) {
				Map map = new HashMap();
				cal.add(Calendar.DAY_OF_MONTH, 7 * j);
				map.put("schedule", sdf.format(cal.getTime()));
				list.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	} 
	
	// 定义锁防止预约与取消并发
	public static final Object lock = "com.txby.register.lock";

	// 分页每页显示数目
	public int itemCount = 30;
	
	// 查询记录
	public List queryItems(TXBYObject obj) {
		List list = QBuilder.db("basedb").queryHql("from " + obj.getClass().getSimpleName() + " where hospital = " + obj.getHospital() + " and status = " + STATUS_ENABLE + " order by cTime desc");
		return list;
	}
	
	// 通过ID查询一条记录
	public List queryItem(TXBYObject obj) {
		List list = QBuilder.db("basedb").queryHql("from " + obj.getClass().getSimpleName() + " where hospital = " + obj.getHospital() + " and id = " + obj.getId() + " and status = " + STATUS_ENABLE);
		return list;
	}
	
	// 添加记录	
	public Integer createItem(TXBYObject obj) {
		Integer id = (Integer)DBTools.db("basedb").addItem(obj);
		return id;
	} 
	 
	// 修改记录
	public boolean modifyItem(TXBYObject obj) {
		List list = queryItem(obj);
		if (list.size() == 0) return false;
		DBTools.db("basedb").modItem(obj, obj.getId());
		return true;
	}
	
	// 提交订单(与商店关联)
	public  Message addOrder(Order order) {
		synchronized(lock){
			Message msg = new Message();
			// 判断预约服务当天是否重复预约
			List<String> orderDates = QBuilder.db("basedb").queryHql("select CONCAT(FROM_UNIXTIME(execTime / 1000, '%Y-%m-%d'), '') from Order where uid = " + order.getUid() + " and serviceId = " + order.getServiceId() + " and hospital = " + order.getHospital());
			String time = DateUtil.formatDate(new Date(order.getExecTime()));
			if (orderDates.contains(time)) { 
				setErrcode(msg, HAVE_COMMITED);
				return msg;
			}
			// 判断商品的合法性（是否存在该商品，库存是否充足）
			List<Shop> list = QBuilder.db("basedb").queryHql("from Shop where hospital = " + order.getHospital() + " and serviceId = " + order.getServiceId() + " and status = " + STATUS_ENABLE);
			if (list.size() == 0) {  // 商品不存在
				setErrcode(msg, NO_RESULT);
				return msg;
			}
			Shop shop = list.get(0);
			int left = shop.getLeft();
			int type = shop.getType();
			int limited = shop.getLimited();
			if (left <= 0) {  // 库存不足
				setErrcode(msg, NO_NUMBER);
				return msg;
			}
			if (type > 0 && limited <= 0) {  // 限号已经全部预约
				setErrcode(msg, NO_NUMBER);
				return msg;
			}
			if (type > 0) {  
				shop.setLimited(--limited);
			}
			if (type > 0 && left <= 0){
				setErrcode(msg, NO_NUMBER);
				return msg;
			}
			shop.setLeft(--left);
			Integer id = createItem(order);
			if(id == null) {
				setErrcode(msg, RESPONSE_FAILED);
			} else {
				DBTools.db("basedb").modItem(shop, shop.getId());  // 插入成功修改商品库存
				msg.put("id", id);
			}
			return msg;
		}
	}
	
	// 删除订单(与商店关联)
	public synchronized Message destroyOrder(Order order) {
		synchronized(lock){
			Message msg = new Message();
			order.setStatus(STATUS_DISABLE);
			if(!modifyItem(order))  {// 修改订单状态
				setErrcode(msg, RESPONSE_FAILED);
				return msg;
			}
			// 判断商品的合法性（是否存在该商品）
			List<Shop> list = QBuilder.db("basedb").queryHql("from Shop where hospital = " + order.getHospital() + " and serviceId = " + order.getServiceId() + " and status = " + STATUS_ENABLE);
			if (list.size() > 0) {  // 商品存在
				Shop shop = list.get(0);
				int left = shop.getLeft();
				int type = shop.getType();
				int limited = shop.getLimited();
				if (type != -1) {   // 是否使用商店-1 不使用，0 不限号服务
					if (type != 0) {    // 判断是否限号
						shop.setLimited(++limited);
					}
					shop.setLeft(++left);
					DBTools.db("basedb").modItem(shop, shop.getId());  // 插入成功修改商品库存
				}
			}
			return msg;
		}
	}
	
	// 提交预约信息
	public Message register(Order order) {
		Message msg = new Message();
		if (order.getHospital() == 1036) {
			// 是否已经预约过
			String time = DateUtil.formatDate(new Date(order.getRegisterTime()));
			List<String> orderDates = QBuilder.db("basedb").queryHql("select CONCAT(FROM_UNIXTIME(registerTime / 1000, '%Y-%m-%d'), '') from Order where uid = " + order.getUid() + " and serviceId = " + order.getServiceId() + " and hospital = " + order.getHospital());
			if (orderDates.contains(time)) { 
				setErrcode(msg, HAVE_COMMITED);
				return msg;
			}
		}
		if (order.getExecTime() != null) {
			// 是否已经预约过（眼科）
			String time = DateUtil.formatDate(new Date(order.getExecTime()));
			List<String> orderDates = QBuilder.db("basedb").queryHql("select CONCAT(FROM_UNIXTIME(execTime / 1000, '%Y-%m-%d'), '') from Order where uid = " + order.getUid() + " and serviceId = " + order.getServiceId() + " and hospital = " + order.getHospital());
			if (orderDates.contains(time)) { 
				setErrcode(msg, HAVE_COMMITED);
				return msg;
			}
		}
		Integer id = createItem(order); // 提交一个预约信息
		if(id == null) {
			setErrcode(msg, RESPONSE_FAILED);
		} else {
			msg.put("id", id);
		}
		return msg;
	}
	
	// 取消预约信息
	public Message destroy(TXBYObject obj) {
		obj.setStatus(STATUS_DISABLE);
		Message msg = new Message();
		if (!modifyItem(obj))
			setErrcode(msg, NO_RESULT);
		return msg;
	}
	
	// 判断重复处理
	public boolean repeatHandle(Order order) {
		// 是否已经处理过
		if (order.getExecTime() == null) 
			return false;
		String time = DateUtil.formatDate(new Date(order.getExecTime()));
		List<String> orderDates = QBuilder.db("basedb").queryHql("select CONCAT(FROM_UNIXTIME(execTime / 1000, '%Y-%m-%d'), '') from Order where uid = " + order.getUid() + " and doctor = " + order.getDoctor() + " and serviceId = " + order.getServiceId() + " and hospital = " + order.getHospital());
		if (orderDates.contains(time)) { 
			return true;
		}
		return false;
	}
	
	// 判断是否已做
	public boolean repeatSubmit(Order order) {
		List list = QBuilder.db("basedb").queryHql("from Order where id = " + order.getId() + " and state = " + order.getStatus());
		if (list.size() > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	// 判断是否已做
	public boolean repeatDo(Order order) {
		List list = QBuilder.db("basedb").queryHql("from Order where id = " + order.getId() + " and state = 3");
		if (list.size() > 0) {
			return true;
		} else {
			return false;
		}
	}
	
%>